package com.badibadi.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.badibadi.infos.Img;
import com.badibadi.infos.Results;
import com.badibadi.infos.ShowTableModel;
import com.badibadi.mail.MailActivity;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.HtmlUtils;
import com.badibadi.mytools.ImageTools;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.RegexUtils;
import com.badibadi.mytools.SinaExpressionTools;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.XUtils;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.SeeApplyFormActivity;
import com.badibadi.adapter.Gridview3Adapter;
import com.libjph.util.JsonUtil;
import com.libjph.util.StringUtil;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

//建立和填写申请表 mail_paizhao activity_mail_send new Html activity_mail_send
public class AddApplyFormActivity extends MailActivity {
	protected static final String TAG = "AddApplyFormActivity";
	private LinearLayout activity_mail_shou_layout,
			activity_mail_zhuzhi_layout;
	private Results results, resultsdd, results2;
	private String con = null, cid = null, apply_id = null;
	private String pan = null;
	private Message message;
	private Bundle bundle;
	// 下面的是照相机的
	private ArrayList<String> pathlist;
	private GridView picGridView;
	ArrayList<Img> imgs;
	Gridview3Adapter picGridView_adapter;
	ArrayList<String> htmp_list;
	// private ShowTableModel showTableModel;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress(AddApplyFormActivity.this);
					Utils.showMessage(AddApplyFormActivity.this, getResources()
							.getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:
				try {
					Utils.ExitPrgress(AddApplyFormActivity.this);
					Utils.showMessage(AddApplyFormActivity.this,
							results.getRetmsg());
				} catch (Exception e) {
					// TODO: handle exception
				}

				try {
					Intent it = new Intent();
					it.putExtra("result", "success");
					setResult(10, it);
					finish();
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				break;
			case 3:
				try {
					Utils.ExitPrgress(AddApplyFormActivity.this);
					Utils.showMessage(AddApplyFormActivity.this, getResources()
							.getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 4://加入俱乐部
				try {
					Utils.ExitPrgress(AddApplyFormActivity.this);
					if(resultsdd.isRet()==true)
					{
						Utils.showMessage(AddApplyFormActivity.this,
								getResources().getString(R.string.wx_add_success));
					}else
					{
						Utils.showMessage(AddApplyFormActivity.this,
								getResources().getString(R.string.wx_txt_51));
					}
					
				} catch (Exception e) {
					// TODO: handle exception
				}
				finish();
				break;
			case 2000:
				Utils.ExitPrgress(AddApplyFormActivity.this);
				Utils.ExitProgress_hen(AddApplyFormActivity.this);
				Utils.showMessage(AddApplyFormActivity.this, getResources()
						.getString(R.string.l_xb18));
				String temp_path = msg.getData().getString("path");
				htmp_list = new ArrayList<String>();
				htmp_list.addAll(fenge(temp_path));

				for (int i = 0; i < htmp_list.size(); i++) {
					// activity_mail_content.setText(activity_mail_content
					// .getText().toString() + list3.get(i));
					// activity_mail_content.setSelection(activity_mail_content
					// .getText().toString().length());
					Img img = new Img();
					String cc = htmp_list.get(i).substring(10,
							htmp_list.get(i).length() - 4);
//					   
					img.setPath(cc);
					imgs.add(img);
				}
				picGridView_adapter.notifyDataSetChanged();

				break;
			case 5:
				try {
					Utils.ExitPrgress(AddApplyFormActivity.this);
					Utils.showMessage(AddApplyFormActivity.this, getResources()
							.getString(R.string.l_xb183));
					finish();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 6:
				try {
					Utils.ExitPrgress(AddApplyFormActivity.this);

					String aa = results2.getRetmsg();

					if (aa != null) {
						//    
						List<String> fir = RegexUtils.getImgSrc(aa);
						List<String> fir2 = RegexUtils.getImgSrcGroup(aa);
						String ss = results2.getRetmsg();
						for (int i = 0; i < fir.size(); i++) {
							if (fir.get(i).indexOf(
									Constants.Fei_biaoqing_qianzui) != -1
									|| fir.get(i).indexOf(
											Constants.Fei_biaoqing_qianzui2) != -1
									|| fir.get(i).indexOf(
											Constants.Fei_biaoqing_qianzui3) != -1
									|| fir.get(i).indexOf(
											Constants.Fei_biaoqing_qianzui4) != -1) {
//								LogUtils.d("fir.get+("+i+")="+fir.get(i)+"fir2.get+("+i+")="+fir2.get(i));
								Img img = new Img();
								img.setPath("" + fir.get(i));
								imgs.add(img);
								ss = ss.replace(fir2.get(i), "");
							} else {
								ss = SinaExpressionTools
										.replaceAllPathToReplace(ss);
							}
						}
						picGridView_adapter.notifyDataSetChanged();
						new HtmlUtils(AddApplyFormActivity.this,
								activity_mail_content, ss).showEditText();
					}

					// }
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;

			default:
				break;
			}
		}
	};

	private ArrayList<String> fenge(String ds) {
		String dg[] = ds.split(",");
		ArrayList<String> list2 = new ArrayList<String>();
		if (dg != null) {
			for (int i = 0; i < dg.length; i++) {
				// <img
				// src='http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/7a/shenshou_thumb.gif'
				// />"
				if (dg[i].startsWith("http")) {
					list2.add("<img src='" + dg[i] + "' />");
				} else {
					list2.add("<img src='" + Constants.BadiDownImgUrl + dg[i]
							+ "' />");
				}

			}
		}
		return list2;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		try {
			pan = getIntent().getStringExtra("pan");
			cid = getIntent().getStringExtra("cid");
			apply_id = getIntent().getStringExtra("apply_id");
		} catch (Exception e) {
			// TODO: handle exception
		}
		picGridView = (GridView) this.findViewById(R.id.picture_GridView);
		picGridView.setHorizontalSpacing(DisplayUtil.dip2px(
				AddApplyFormActivity.this, 5));
		picGridView.setVerticalSpacing(DisplayUtil.dip2px(
				AddApplyFormActivity.this, 5));
		imgs = new ArrayList<Img>();
		htmp_list = new ArrayList<String>();
		picGridView_adapter = new Gridview3Adapter(AddApplyFormActivity.this,
				imgs);
		picGridView.setAdapter(picGridView_adapter);
		picGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AddApplyFormActivity.this,
						ShowViewPagerActivity.class);
				intent.putStringArrayListExtra("pic",
						(ArrayList<String>) picGridView_adapter.getSList());
//				for(int i=0;i<picGridView_adapter.getSList().size();i++)
//				{
//					LogUtils.e("pic="+picGridView_adapter.getSList().get(i));
//				}
				
				
				intent.putExtra("position", position);
				startActivity(intent);
			}
		});
		// picGridView.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// picGridView_adapter.getItem(position)
		// }
		// });
		pathlist = new ArrayList<String>();
		activity_mail_zhuzhi_layout = (LinearLayout) findViewById(R.id.activity_mail_zhuzhi_layout);
		activity_mail_shou_layout = (LinearLayout) findViewById(R.id.activity_mail_shou_layout);
		pathlist = new ArrayList<String>();
		activity_mail_send = (TextView) findViewById(R.id.activity_mail_send);
		title_mail = (TextView) findViewById(R.id.title_mail);
		btn_paizhao = (ImageButton) findViewById(R.id.mail_paizhao);
		btn_paizhao.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AddApplyFormActivity.this,
						SelectPictsMail_Activity.class);
				intent.putExtra("panduan", "no_set");
				startActivityForResult(intent, 3);
			}
		});
		activity_mail_shou_layout.setVisibility(View.GONE);
		activity_mail_zhuzhi_layout.setVisibility(View.GONE);
		if (pan != null && pan.equals("set")) {
			activity_mail_send.setText(getResources().getString(R.string.Send));
			title_mail.setText(getResources().getString(R.string.l_xb19));
		} else {
			activity_mail_send.setText(getResources().getString(R.string.Save));
			title_mail.setText(getResources().getString(R.string.l_xb20));
		}
		if (pan != null && pan.equals("set")) {
			showTable(Utils.getUid(AddApplyFormActivity.this), cid, apply_id);
		}
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		super.init();
		activity_mail_titalimg.setVisibility(View.GONE);

		activity_mail_send.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				con = activity_mail_content.getText().toString().trim();
				StringBuffer buff = new StringBuffer(con);

				if (pan != null && pan.equals("set")) {// 这部分是申请进入别人俱乐部需要填写的数据
					if (con != null) {

						if (!StringUtil.isNullOrEmpty(con)) {
							if (imgs != null && !imgs.isEmpty()) {
								buff.append("<div>");
								for (int i = 0; i < imgs.size(); i++) {
									buff.append(Utils.toMailHtmL(imgs.get(i)
											.getPath()));
//									   
								}
								buff.append("<div style='clear:both;'></div></div>");
							}
							String content3 = buff.toString().trim();
//							   
							String content2 = SinaExpressionTools
									.replaceAllReplaceToPath(content3);
							content2 = content2.replaceAll("\\[", "");
							content2 = content2.replaceAll("\\]", "");

//							   
							Add_club(cid, "1", content2);
						} else {
							Utils.showMessage(AddApplyFormActivity.this,
									getResources().getString(R.string.l_xb21));
						}
						//    

					} else {
						Toast.makeText(getApplicationContext(),
								getResources().getString(R.string.l_xb21), 0)
								.show();
					}
				} else {// 这是创建俱乐部使用的
					if (con != null) {

						if (!StringUtil.isNullOrEmpty(con)) {
							if (imgs != null && !imgs.isEmpty()) {
								buff.append("<div>");
								for (int i = 0; i < imgs.size(); i++) {
									buff.append(Utils.toMailHtmL(imgs.get(i)
											.getPath()));
								}
								buff.append("<div style='clear:both;'></div></div>");
							}
							String content3 = buff.toString().trim();
//							   
							String content2 = SinaExpressionTools
									.replaceAllReplaceToPath(content3);
							content2 = content2.replaceAll("\\[", "");
							content2 = content2.replaceAll("\\]", "");

							//    
							applyTable(content2);
						} else {
							Utils.showMessage(AddApplyFormActivity.this,
									getResources().getString(R.string.l_xb21));
						}

					} else {
						Toast.makeText(getApplicationContext(),
								getResources().getString(R.string.l_xb21), 0)
								.show();
					}
				}
			}
		});
	}

	/**
	 * 查看申请表详细页面-----POST
	 * 
	 * @param $uid
	 *            //用户ID
	 * @param $cid
	 *            //俱乐部ID
	 * @param $apply
	 *            //申请表id
	 */
	public void showTable(final String uid, final String cid, final String apply) {
		//    
		Utils.showPrgress(AddApplyFormActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				// map.put("uid", uid);
				map.put("cid", cid);
				// map.put("apply", apply);
//				   
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "web/createClubTableShow");
//				   
				if (content != null) {
					results2 = Utils.checkResult_NNN(AddApplyFormActivity.this,
							content);
					if (results2 != null
							&& !results2.getRetmsg().equals("null")
							&& results2.isRet() == true) {
//						   
						handler.sendEmptyMessage(6);
						// try {
						// showTableModel = JsonUtil.getEntityByJsonString(
						// results.getRetmsg(), ShowTableModel.class);
						// // showDisscuss=discuss.getDiscu().get(0);
						// //
						// activityReadingModel=JsonUtil.getEntityByJsonString(results.getRetmsg(),
						// // ActivityReadingModel.class);
						// handler.sendEmptyMessage(2);
						// } catch (Exception e) {
						//    
						// handler.sendEmptyMessage(5);
						// }
					} else {
						handler.sendEmptyMessage(5);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});

	}

	private void applyTable(final String content) {
		Utils.showPrgress(AddApplyFormActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(AddApplyFormActivity.this));
				map.put("content", content);
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "club/applyTable");
				if (content != null) {
					results = Utils.checkResult_NNN(getApplicationContext(),
							content);
//					   ("建立申请表返回的参数是:" + content + " "
//							+ results.getRetmsg());
					if (results != null && !results.getRetmsg().equals("null")
							&& results.isRet()) {
						handler.sendEmptyMessage(2);
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		//    
		if (arg0 == 3 && arg1 == SelectPictsMail_Activity.HUICHUAN_KEY_1) {
			if (arg2 != null) {
				pathlist = arg2.getStringArrayListExtra("files");

				XUtils.UpImg_ceshi_douhaoXUtils(pathlist,
						AddApplyFormActivity.this, handler);
			}
		}
		super.onActivityResult(arg0, arg1, arg2);
	}

	private void Add_club(final String cid, final String is_apply,
			final String content) {
		try {
			Utils.showPrgress(AddApplyFormActivity.this);
		} catch (Exception e) {
			// TODO: handle exception
		}
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(AddApplyFormActivity.this));
				map.put("cid", cid);
				map.put("is_apply", is_apply);
				if (is_apply.equals("1")) {
					map.put("contents", content);
				}
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "club/attendClub");
				if (content != null) {
					resultsdd = Utils.checkResult_NNN(getApplicationContext(),
							content);
//					   ("加入俱乐部返回的参数是:" + content + " "
//							+ resultsdd.getRetmsg());
					if (resultsdd != null
							&& !resultsdd.getRetmsg().equals("null")) {
						handler.sendEmptyMessage(4);
					} else {
						handler.sendEmptyMessage(1);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}
}
